//JavaScript代码区域
layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    laydate.render({
        elem: "#start_date"
    })
    laydate.render({
        elem: "#end_date"
    })
    $(function () {
        getCode();
        getRoleList();
        tableRender();
        form.render();
    })
    $("#find").click(function () {
        tableRender();
    })
    $("#clear").click(function () {
        $(".search_input").val("");
    })

    function tableRender() {
        table.render({
            elem: '#demo'
            // , height: 312
            ,
            url: LOCALHOSTURL + '/user/user/getUsers' //数据接口
            ,
            method: "get",
            where: {
                "param": $("#param").val(),
                "sex": $("#sex").find("option:selected").val(),
                "graduate": $("#graduate").find("option:selected").val(),
                "role": $("#role").find("option:selected").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true, //开启分页
            title: "用户表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'code',
                    title: '用户编号'
                }, {
                    field: 'name',
                    title: '用户姓名',
                    templet: function (res) {
                        if (res.name == null)
                            return '暂无';
                        else
                            return res.name;
                    }
                }, {
                    field: 'phone',
                    title: '电话',
                    templet: function (res) {
                        if (res.phone == null)
                            return '暂无';
                        else
                            return res.phone;
                    }
                }, {
                    field: 'address',
                    title: '所在地址',
                    templet: function (res) {
                        if (res.address == null)
                            return '暂无';
                        else
                            return res.address;
                    }
                }, {
                    field: 'sex',
                    title: '性别',
                    templet: function (res) {
                        if (res.sex == null)
                            return '暂无';
                        else
                            return res.sexName;
                    }
                }, {
                    field: 'graduate',
                    title: '学历',
                    templet: function (res) {
                        if (res.graduate == null)
                            return '暂无';
                        else
                            return res.graduateName;
                    }
                }, {
                    field: 'entranceTime',
                    title: '入学时间',
                    sort: true,
                    templet: function (res) {
                        if (res.entranceTime == null)
                            return '暂无';
                        else
                            return res.entranceTime;
                    }
                },{
                    field: 'role',
                    title: '角色',
                    templet: function (res) {
                        if (res.role == null)
                            return '暂无';
                        else
                            return res.roleName;
                    }
                }, {
                    field: 'icon',
                    title: '头像',
                    templet: function (res) {
                        return '<img class="layui-nav-img" width="30px" height="30px" src="' + res.icon + '"/>'
                    }
                }, {
                    field: 'status',
                    title: '状态'
                }, {
                    fixed: 'right',
                    title: '操作',
                    toolbar: '#barDemo',
                    width: 100
                }
                ]
            ]
        });
    }

    //第一个实例

    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 2,
                    title: "添加用户信息",
                    area: ['100%', '100%'],
                    content: ["editUser.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = layero.find('iframe')[0].contentWindow;
                        console.log(iframeWin);
                        iframeWin.editUser("",index);
                    }
                })
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(demo)', function (obj) {
        var data = obj.data;
        console.log(obj);
        if (obj.event === 'del') {
            layer.confirm("真的删除用户" + data.code + "?", function (index) {
                // obj.del();
                let result = myAjax("/user/user/deleteUser", "get", {code: data.code});
                alert(result.message);
                tableRender();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            // layer.alert(JSON.stringify(obj.data));
            layer.open({
                type: 2,
                title: "修改用户信息",
                area: ['100%', '100%'],
                content: ["editUser.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = layero.find('iframe')[0].contentWindow;
                    console.log(iframeWin);
                    iframeWin.editUser(data,index);
                }
            })
        }
    });

    form.on('switch(status)', function (obj) {
        var data = obj.value;
        var checked = obj.elem.checked;
        let result = "";
        if (checked) {
            result = myAjax("/user/user/updateStatus", "post", {"code": data, "status": 'normal'});
        } else {
            result = myAjax("/user/user/updateStatus", "post", {"code": data, "status": 'frozen'});
        }
        console.log(result.data);
        // tableRender();
    });

    //获取码表数据
    function getCode() {
        let data = null;
        if (sessionStorage.getItem("code") != null) {
            data = JSON.parse(sessionStorage.getItem("code"));
        } else {
            let result = ajaxModel("/user/user/getCodeList", "get");
            data = result.data;
            sessionStorage.setItem("code", JSON.stringify(data));
        }
        console.log(data);
        $("#sex").html("<option value=''>全部</option>");
        $.each(data.sex, function (i, sex) {
            $("#sex").append("<option value='" + sex.code + "'>" + sex.name + "</option>");
        })
        $("#graduate").html("<option value=''>全部</option>");
        $.each(data.graduate, function (i, graduate) {
            $("#graduate").append("<option value='" + graduate.code + "'>" + graduate.name + "</option>");
        })
    }

    function getRoleList() {
        let data = null;
        if (sessionStorage.getItem("role") != null) {
            data = JSON.parse(sessionStorage.getItem("role"));
        } else {
            let result = ajaxModel("/role/role/getRoleList", "get");
            data = result.data;
            sessionStorage.setItem("role", JSON.stringify(data));
        }
        console.log(data);
        $("#role").html("<option value=''>全部</option>");
        $.each(data, function (i, role) {
            $("#role").append("<option value='" + role.id + "'>" + role.name + "</option>");
        });
    }
});
